﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace KnowledgeAssistant
{
    public partial class KnowledgeAssistantForm : Form
    {
        private LoginForm lf;
        private bool useLoginForm;
        private User user = null;

        public KnowledgeAssistantForm(bool useLoginForm)
        {
            InitializeComponent();
            this.useLoginForm = useLoginForm;
        }
        public void StartWithLoginForm()
        {
            this.lf = new LoginForm();
            this.lf.StartPosition = FormStartPosition.CenterScreen;
            this.lf.ShowDialog();
            if (lf.IsLogIn())
            {
                this.user = lf.User;
            }
        }
        public bool IsLoginIn()
        {
            if (this.lf != null)
            {
                return this.lf.IsLogIn();
            }
            return false;
        }
        public void RunLoginForm()
        {
            if (useLoginForm)
            {
                StartWithLoginForm();

                if (!this.lf.IsLogIn())
                {
                    this.Close();
                }
            }
        }
        public User User
        {
            get { return this.user; }
            set { this.user = value; }
        }
        private void KnowledgeAssistantForm_Load(object sender, EventArgs e)
        {
            RefreshData();
        }

        public void VisualizeControls()
        {
            DisableControls();
            if (user != null)
            {
                foreach (Permission p in this.user.Role.Permissions)
                {
                    switch (p.Type)
                    {
                        case PermissionType.all: EnableControls(); break;
                        case PermissionType.statisticsall: EnableStatisticsControls(); break;
                        case PermissionType.subjectall: EnableSubjectControls(); break;
                        case PermissionType.testall: EnableTestControls(); break;
                        case PermissionType.themeall: EnableThemeControls(); break;
                        case PermissionType.adminall: EnableAdminControls(); break;
                        case PermissionType.adminroles:
                            adminMenuItem.Visible = true;
                            adminMenuItem.Enabled = true;
                            rolesMenuItem.Enabled = true;
                            rolesMenuItem.Visible = true;
                            break;
                        case PermissionType.adminusers:
                            adminMenuItem.Visible = true;
                            adminMenuItem.Enabled = true;
                            usersMenuItem.Enabled = true;
                            usersMenuItem.Visible = true;
                            break;
                        case PermissionType.adminstudentsview:
                            adminMenuItem.Visible = true;
                            adminMenuItem.Enabled = true;
                            studentsMenuItem.Enabled = true;
                            studentsMenuItem.Visible = true;
                            break;
                        case PermissionType.adminteachersview:
                            adminMenuItem.Visible = true;
                            adminMenuItem.Enabled = true;
                            teachersMenuItem.Enabled = true;
                            teachersMenuItem.Visible = true;
                            break;

                        //case PermissionType.testadd:
                        //    testItem.Visible = true;
                        //    testItem.Enabled = true;
                        //    addTestItem.Enabled = true;
                        //    addTestItem.Visible = true;
                        //    break;
                        //case PermissionType.testedit:
                        //    testItem.Visible = true;
                        //    testItem.Enabled = true;
                        //    editTestItem.Enabled = true;
                        //    editTestItem.Visible = true;
                        //    break;
                        //case PermissionType.testremove:
                        //    testItem.Visible = true;
                        //    testItem.Enabled = true;
                        //    removeTestItem.Enabled = true;
                        //    removeTestItem.Visible = true;
                        //    break;

                        case PermissionType.testrun:
                            //testItem.Visible = true;
                            //testItem.Enabled = true;
                            //runTestItem.Visible = true;
                            //runTestItem.Enabled = true;
                            runTestButton.Enabled = true;
                            runTestButton.Visible = true;
                            break;
                        case PermissionType.subjectadd:
                            //subjectItem.Enabled = true;
                            //subjectItem.Visible = true;
                            //addSubjectItem.Enabled = true;
                            //addSubjectItem.Visible = true;
                            addsubject.Enabled = true;
                            addsubject.Visible = true;
                            break;
                        case PermissionType.subjectedit:
                            //subjectItem.Enabled = true;
                            //subjectItem.Visible = true;
                            //editSubjectItem.Enabled = true;
                            //editSubjectItem.Visible = true;
                            editsubject.Enabled = true;
                            editsubject.Visible = true;
                            break;
                        case PermissionType.subjectremove:
                            //subjectItem.Enabled = true;
                            //subjectItem.Visible = true;
                            //removeSubjectItem.Enabled = true;
                            //removeSubjectItem.Visible = true;
                            removesubject.Enabled = true;
                            removesubject.Visible = true;
                            break;

                        case PermissionType.themeadd:
                            //themeItem.Enabled = true;
                            //themeItem.Visible = true;
                            //addThemeItem.Enabled = true;
                            //addThemeItem.Visible = true;
                            addtheme.Enabled = true;
                            addtheme.Visible = true;
                            break;
                        case PermissionType.themeedit:
                            //themeItem.Enabled = true;
                            //themeItem.Visible = true;
                            //editThemeItem.Enabled = true;
                            //editThemeItem.Visible = true;
                            edittheme.Enabled = true;
                            edittheme.Visible = true;
                            break;
                        case PermissionType.themeremove:
                            //themeItem.Enabled = true;
                            //themeItem.Visible = true;
                            //removeThemeItem.Enabled = true;
                            //removeThemeItem.Visible = true;
                            removetheme.Enabled = true;
                            removetheme.Visible = true;
                            break;

                        case PermissionType.statisticsallstat:
                            statisticsItem.Visible = true;
                            statisticsItem.Enabled = true;
                            allStatisticsItem.Enabled = true;
                            allStatisticsItem.Visible = true;
                            break;
                        case PermissionType.statisticsgroup:
                            statisticsItem.Visible = true;
                            statisticsItem.Enabled = true;
                            groupStatisticsItem.Enabled = true;
                            groupStatisticsItem.Visible = true;
                            break;
                        case PermissionType.statisticsstudent:
                            statisticsItem.Visible = true;
                            statisticsItem.Enabled = true;
                            studentStatisticsItem.Enabled = true;
                            studentStatisticsItem.Visible = true;
                            break;
                        case PermissionType.statisticsmy:
                            statisticsItem.Visible = true;
                            statisticsItem.Enabled = true;
                            myStatisticsItem.Enabled = true;
                            myStatisticsItem.Visible = true;
                            break;
                    }
                }
            }
        }

        private void DisableControls()
        {
            DisableStatisticsControls();
            DisableTestControls();
            DisableSubjectControls();
            DisableThemeControls();
            DisableAdminControls();
        }
        private void EnableControls()
        {
            EnableStatisticsControls();
            EnableTestControls();
            EnableSubjectControls();
            EnableThemeControls();
            EnableAdminControls();
        }

        private void EnableStatisticsControls()
        {
            //Statistics items
            statisticsItem.Enabled = true;
            statisticsItem.Visible = true;

            groupStatisticsItem.Enabled = true;
            groupStatisticsItem.Visible = true;

            studentStatisticsItem.Enabled = true;
            studentStatisticsItem.Visible = true;

            myStatisticsItem.Enabled = true;
            myStatisticsItem.Visible = true;

            allStatisticsItem.Enabled = true;
            allStatisticsItem.Visible = true;
        }
        private void EnableTestControls()
        {
            //testItem.Enabled = true;
            //testItem.Visible = true;

            //editTestItem.Enabled = true;
            //editTestItem.Visible = true;

            //addTestItem.Enabled = true;
            //addTestItem.Visible = true;

            runTestButton.Enabled = true;
            runTestButton.Visible = true;

            //removeTestItem.Enabled = true;
            //removeTestItem.Visible = true;
        }
        private void EnableSubjectControls()
        {
            //subjectItem.Enabled = true;
            //subjectItem.Visible = true;

            //editSubjectItem.Enabled = true;
            //editSubjectItem.Visible = true;

            //addSubjectItem.Enabled = true;
            //addSubjectItem.Visible = true;

            //removeSubjectItem.Enabled = true;
            //removeSubjectItem.Visible = true;

            editsubject.Enabled = true;
            editsubject.Visible = true;

            addsubject.Enabled = true;
            addsubject.Visible = true;

            removesubject.Enabled = true;
            removesubject.Visible = true;
        }
        private void EnableThemeControls()
        {
            //themeItem.Enabled = true;
            //themeItem.Visible = true;

            //editThemeItem.Enabled = true;
            //editThemeItem.Visible = true;

            //addThemeItem.Enabled = true;
            //addThemeItem.Visible = true;

            //removeThemeItem.Enabled = true;
            //removeThemeItem.Visible = true;

            edittheme.Enabled = true;
            edittheme.Visible = true;

            addtheme.Enabled = true;
            addtheme.Visible = true;

            removetheme.Enabled = true;
            removetheme.Visible = true;
        }
        private void EnableAdminControls()
        {
            adminMenuItem.Enabled = true;
            adminMenuItem.Visible = true;

            usersMenuItem.Enabled = true;
            usersMenuItem.Visible = true;

            rolesMenuItem.Enabled = true;
            rolesMenuItem.Visible = true;

            studentsMenuItem.Enabled = true;
            studentsMenuItem.Visible = true;

            teachersMenuItem.Enabled = true;
            teachersMenuItem.Visible = true;

        }

        private void DisableStatisticsControls()
        {
            //Statistics items
            statisticsItem.Enabled = false;
            statisticsItem.Visible = false;

            groupStatisticsItem.Enabled = false;
            groupStatisticsItem.Visible = false;

            studentStatisticsItem.Enabled = false;
            studentStatisticsItem.Visible = false;

            myStatisticsItem.Enabled = false;
            myStatisticsItem.Visible = false;

            allStatisticsItem.Enabled = false;
            allStatisticsItem.Visible = false;
        }
        private void DisableTestControls()
        {
            //testItem.Enabled = false;
            //testItem.Visible = false;

            //editTestItem.Enabled = false;
            //editTestItem.Visible = false;

            //addTestItem.Enabled = false;
            //addTestItem.Visible = false;

            runTestButton.Enabled = false;
            runTestButton.Visible = false;

            //removeTestItem.Enabled = false;
            //removeTestItem.Visible = false;


            runTestButton.Visible = false;
            runTestButton.Enabled = false;

        }
        private void DisableSubjectControls()
        {
            //subjectItem.Enabled = false;
            //subjectItem.Visible = false;

            //editSubjectItem.Enabled = false;
            //editSubjectItem.Visible = false;

            //addSubjectItem.Enabled = false;
            //addSubjectItem.Visible = false;

            //removeSubjectItem.Enabled = false;
            //removeSubjectItem.Visible = false;

            editsubject.Enabled = false;
            editsubject.Visible = false;

            addsubject.Enabled = false;
            addsubject.Visible = false;

            removesubject.Enabled = false;
            removesubject.Visible = false;
        }
        private void DisableThemeControls()
        {
            //themeItem.Enabled = false;
            //themeItem.Visible = false;

            //editThemeItem.Enabled = false;
            //editThemeItem.Visible = false;

            //addThemeItem.Enabled = false;
            //addThemeItem.Visible = false;

            //removeThemeItem.Enabled = false;
            //removeThemeItem.Visible = false;

            edittheme.Enabled = false;
            edittheme.Visible = false;

            addtheme.Enabled = false;
            addtheme.Visible = false;

            removetheme.Enabled = false;
            removetheme.Visible = false;
        }
        private void DisableAdminControls()
        {
            adminMenuItem.Enabled = false;
            adminMenuItem.Visible = false;

            usersMenuItem.Enabled = false;
            usersMenuItem.Visible = false;

            rolesMenuItem.Enabled = false;
            rolesMenuItem.Visible = false;

            studentsMenuItem.Enabled = false;
            studentsMenuItem.Visible = false;

            teachersMenuItem.Enabled = false;
            teachersMenuItem.Visible = false;
        }

        private void addsubject_Click(object sender, EventArgs e)
        {
            int a = subjectsComboBox.Items.Count;
            Subject subject = (Subject)subjectsComboBox.SelectedItem;
            EditSubject adds = new EditSubject(EditSubject.ActionType.add);
            adds.ShowDialog();
            RefreshData();
            int b = subjectsComboBox.Items.Count;
            if (b > a)
            {
                int max = 0;
                foreach (Subject s in subjectsComboBox.Items)
                {
                    if (s.SubjectID > max)
                    {
                        max = s.SubjectID;
                        subjectsComboBox.SelectedItem = s;
                        themesComboBox.DataSource = ThemeUtil.GetAllThemes(s.SubjectID);
                    }
                }
            }
            else
            foreach (Subject s in subjectsComboBox.Items)
            {
                if (s.SubjectID == subject.SubjectID)
                {
                    subjectsComboBox.SelectedItem = s;
                    themesComboBox.DataSource = ThemeUtil.GetAllThemes(s.SubjectID);
                }
            }
        }

        private void subjectsComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            Subject subj = (Subject)subjectsComboBox.SelectedValue;
            themesComboBox.DataSource = ThemeUtil.GetAllThemes(subj.SubjectID);
            themesComboBox.DisplayMember = "Name";
            if (themesComboBox.Items.Count == 0)
            {
                themesComboBox.Text = "";
            }
        }

        private void RefreshData()
        {
            string user_name = null;
            if (user.Owner is Student)
            { user_name = ((Student)user.Owner).FullName; }
            else if (user.Owner is Teacher)
            { user_name = ((Teacher)user.Owner).FullName; }
            else
            { user_name = "Администратор"; }
            this.user_label.Text = "Вы вошли как " + user_name;

            //Subjects,Themes,Tests
            subjectsComboBox.DataSource = SubjectUtil.GetAllSubjects();
            subjectsComboBox.DisplayMember = "Name";
            if (subjectsComboBox.Items.Count != 0)
            {
                subjectsComboBox.SelectedIndex = 0;
            }
        }

        private void editsubject_Click(object sender, EventArgs e)
        {
            Subject subject = (Subject)subjectsComboBox.SelectedItem;
            EditSubject es = new EditSubject(subject, EditSubject.ActionType.edit);
            es.ShowDialog();
            RefreshData();
            foreach (Subject s in subjectsComboBox.Items)
            {
                if (s.SubjectID == subject.SubjectID)
                {
                    subjectsComboBox.SelectedItem = s;
                    themesComboBox.DataSource = ThemeUtil.GetAllThemes(s.SubjectID);

                }
            }
        }

        private Boolean foundThemeInSubject(int subject_id)
        {
            List<string> param = new List<string>() { };
            param.Add(subject_id.ToString());
            int s_id = 0;

            DataTable table = DatabaseConnect.execSP("GetOneThemeForCheck", param).Tables[0];
            foreach (DataRow row in table.Rows)
            {
                s_id = (int)row["subject_id"];
                if (s_id == subject_id)
                {
                    return true;
                }
                else return false;
            }
            return false;
        }

        private void removesubject_Click(object sender, EventArgs e)
        {
            Subject s = (Subject)subjectsComboBox.SelectedItem;

            if (foundThemeInSubject(s.SubjectID))
            {
                DialogResult dr = MessageBox.Show("У выбранного предмета имеются сохраненные темы. Вы настаиваете на полном удалении?", "Удаление предмета со списком тем", MessageBoxButtons.YesNo);
                if (dr == System.Windows.Forms.DialogResult.Yes)
                {
                    SubjectUtil.RemoveSubject(s.SubjectID);
                    MessageBox.Show("Предмет удален!");
                }
            }

            else
            {
                DialogResult dr = MessageBox.Show("Удалить предмет из базы?", "Удаление предмета", MessageBoxButtons.YesNo);
                if (dr == System.Windows.Forms.DialogResult.Yes)
                {
                    SubjectUtil.RemoveSubject(s.SubjectID);
                }
            }
            RefreshData();
            foreach (Subject subject in subjectsComboBox.Items)
            {
                if (s.SubjectID == subject.SubjectID)
                {
                    subjectsComboBox.SelectedItem = subject;
                    themesComboBox.DataSource = ThemeUtil.GetAllThemes(subject.SubjectID);

                }
            }
        }

        private void addtheme_Click(object sender, EventArgs e)
        {
            /*
             EditSubject adds = new EditSubject(EditSubject.ActionType.add);
             adds.ShowDialog();
             RefreshData();
             int b = subjectsComboBox.Items.Count;
             if (b > a)
             {
                 int max = 0;
                 foreach (Subject s in subjectsComboBox.Items)
                 {
                     if (s.SubjectID > max)
                     {
                         max = s.SubjectID;
                         subjectsComboBox.SelectedItem = s;
                         themesComboBox.DataSource = ThemeUtil.GetAllThemes(s.SubjectID);
                     }
                 }
             }
             else
             foreach (Subject s in subjectsComboBox.Items)
             {
                 if (s.SubjectID == subject.SubjectID)
                 {
                     subjectsComboBox.SelectedItem = s;
                     themesComboBox.DataSource = ThemeUtil.GetAllThemes(s.SubjectID);
                 }
             }
            
            
             */



            
            Theme theme = (Theme)themesComboBox.SelectedItem;
            Subject subject = (Subject)this.subjectsComboBox.SelectedItem;
            if (subject != null)
            {
                int a = themesComboBox.Items.Count;
                EditTheme et = new EditTheme(EditTheme.ActionType.add, subject);
                et.ShowDialog();
                RefreshData();

                subjectsComboBox.SelectedItem = subject;
                themesComboBox.DataSource = ThemeUtil.GetAllThemes(subject.SubjectID);
                int b = themesComboBox.Items.Count;

                if (b > a)
                {
                    int max = 0;
                    foreach (Subject s in subjectsComboBox.Items)
                    {
                        if (s.SubjectID == subject.SubjectID)
                        {
                            subjectsComboBox.SelectedItem = s;
                            themesComboBox.DataSource = ThemeUtil.GetAllThemes(s.SubjectID);
                            foreach (Theme t in themesComboBox.Items)
                            {
                                if (t.ThemeID > max)
                                {
                                    max = t.ThemeID;
                                    themesComboBox.SelectedItem = t;
                                }
                            }
                        }
                    }
                }
                else
                {
                    if (theme != null)
                    {
                        foreach (Subject s in subjectsComboBox.Items)
                        {
                            if (s.SubjectID == subject.SubjectID)
                            {
                                subjectsComboBox.SelectedItem = s;
                                themesComboBox.DataSource = ThemeUtil.GetAllThemes(s.SubjectID);
                                foreach (Theme t in themesComboBox.Items)
                                {
                                    if (t.ThemeID == theme.ThemeID)
                                    {
                                        themesComboBox.SelectedItem = t;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        private void edittheme_Click(object sender, EventArgs e)
        {
            Theme theme = (Theme)themesComboBox.SelectedItem;
            if (theme != null)
            {
                TestEditorForm et = new TestEditorForm(theme);
                et.ShowDialog();
                RefreshData();
                foreach (Subject s in subjectsComboBox.Items)
                {
                    if (s.Name == theme.Subject.Name)
                    {
                        subjectsComboBox.SelectedItem = s;
                        foreach (Theme t in themesComboBox.Items)
                        {
                            if (t.Name == theme.Name)
                            {
                                themesComboBox.SelectedItem = t;
                            }
                        }
                    }
                }
            }
        }

        private Boolean foundQuestionInTheme(int theme_id)
        {
            List<string> param = new List<string>() { };
            param.Add(theme_id.ToString());
            int t_id = 0;

            DataTable table = DatabaseConnect.execSP("GetOneQuestionForCheck", param).Tables[0];
            foreach (DataRow row in table.Rows)
            {
                t_id = (int)row["theme_id"];
                if (t_id == theme_id)
                {
                    return true;
                }
                else return false;
            }
            return false;
        }

        private void removetheme_Click(object sender, EventArgs e)
        {
            Theme t = (Theme)themesComboBox.SelectedItem;
            if (t != null)
            {
                if (foundQuestionInTheme(t.ThemeID))
                {
                    DialogResult dr = MessageBox.Show("У выбранной темы имеются сохраненные вопросы. Продолжить удаление?", "Удаление темы со списком вопросов", MessageBoxButtons.YesNo);
                    if (dr == System.Windows.Forms.DialogResult.Yes)
                    {
                        ThemeUtil.Removetheme(t.ThemeID);
                    }

                }
                else
                {
                    DialogResult dr = MessageBox.Show("Удалить тему из базы?", "Удаление темы", MessageBoxButtons.YesNo);
                    if (dr == System.Windows.Forms.DialogResult.Yes)
                    {
                        ThemeUtil.Removetheme(t.ThemeID);
                    }
                }

                RefreshData();
                foreach (Subject s in subjectsComboBox.Items)
                {
                    if (s.Name == t.Subject.Name)
                    {
                        subjectsComboBox.SelectedItem = s;
                        foreach (Theme th in themesComboBox.Items)
                        {
                            if (th.Name == t.Name)
                            {
                                themesComboBox.SelectedItem = th;
                            }
                        }
                    }
                }
            }
        }

        private void runTestButton_Click(object sender, EventArgs e)
        {
            TestProcessForm tpf = new TestProcessForm((Theme)this.themesComboBox.SelectedItem, this.user.ID, this.user);
            tpf.ShowDialog();
        }

        private void usersMenuItem_Click(object sender, EventArgs e)
        {
            UsersForm uf = new UsersForm();
            uf.ShowDialog();
        }

        private void rolesMenuItem_Click(object sender, EventArgs e)
        {
            RolesForm rf = new RolesForm();
            rf.ShowDialog();
        }

        private void myStatisticsItem_Click(object sender, EventArgs e)
        {
            StatisticsForm sf = new StatisticsForm(this.user.ID, 0, 0, this.user);
            sf.ShowDialog();
        }

        private void allStatisticsItem_Click(object sender, EventArgs e)
        {
            StatisticsForm sf = new StatisticsForm(0, 0, 0, this.user);
            sf.ShowDialog();
        }

        private void groupStatisticsItem_Click(object sender, EventArgs e)
        {
            SelectGroupStudentForStatisticsForm sgs = new SelectGroupStudentForStatisticsForm(SelectGroupStudentForStatisticsForm.LoadType.group);
            sgs.ShowDialog();
            if (sgs.GroupID != 0 && sgs.GroupID != null)
            {
                StatisticsForm sf = new StatisticsForm(0, sgs.GroupID, 0, this.user);
                sf.ShowDialog();
            }

        }

        private void studentStatisticsItem_Click(object sender, EventArgs e)
        {
            SelectGroupStudentForStatisticsForm sgs = new SelectGroupStudentForStatisticsForm(SelectGroupStudentForStatisticsForm.LoadType.student);
            sgs.ShowDialog();
            if (sgs.UserID != 0 && sgs.UserID != null)
            {
                StatisticsForm sf = new StatisticsForm(sgs.UserID, 0, 0, this.user);
                sf.ShowDialog();
            }
        }

        private void studentsMenuItem_Click(object sender, EventArgs e)
        {
            StudentsForm sf = new StudentsForm();
            sf.ShowDialog();
        }

        private void teachersMenuItem_Click(object sender, EventArgs e)
        {
            TeachersForm tf = new TeachersForm();
            tf.ShowDialog();
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            LoginForm lf = new LoginForm();
            lf.ShowDialog();

            if (lf.IsLogIn())
            {
                this.user = lf.User;
                this.VisualizeControls();
                RefreshData();
            }
        }

        private void выходToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            ChangeLoginPassForm clpf = new ChangeLoginPassForm(user.ID);
            clpf.ShowDialog();
        }

        private void соединениеСБДToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CryptConfigForm ccf = new CryptConfigForm();
            ccf.ShowDialog();

        }

        private void themesComboBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                runTestButton_Click(sender, e);
            }
        }
    }
}
